package com.lixin.smartclassroom.ui.home.tab1.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.widget.TextSwitcher
import androidx.core.widget.doAfterTextChanged
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeNet
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.getpingjiatimu
import com.lixin.smartclassroom.api.gettimu
import com.lixin.smartclassroom.api.shangchaunfile
import com.lixin.smartclassroom.api.submittimu
import com.lixin.smartclassroom.api.uploadFiles
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.bean.FileBean
import com.lixin.smartclassroom.bean.Options
import com.lixin.smartclassroom.bean.TopicListDto2
import com.lixin.smartclassroom.common.saveSuccessDialog
import com.lixin.smartclassroom.databinding.ActivityPracticeAnswerBinding
import com.lixin.smartclassroom.ui.home.adapter.choiceQuestionAnswer
import com.lixin.smartclassroom.ui.home.adapter.moreChoiceQuestionAnswer
import com.lixin.smartclassroom.ui.home.adapter.selectImages
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.base.RxManager
import com.lixinkeji.extension.dp2px
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.setRoundRectBg
import com.lixinkeji.extension.start
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import com.luck.picture.lib.entity.LocalMedia
import java.io.File
import java.util.Collections


/**
 * Description 练习答题
 * Author: lwc
 * Date:2023/12/13 11:21
 */
class PracticeAnswerAct : BaseActivity<ActivityPracticeAnswerBinding>() {
    override fun getViewBinding() = ActivityPracticeAnswerBinding.inflate(layoutInflater)

    override fun topBarHide() = true
    override fun startPadding() = false
    private lateinit var listBean: ArrayList<DataListBean>
    private lateinit var listBeanAnswer: ArrayList<TopicListDto2>

    private var localMediaList = java.util.ArrayList<LocalMedia>()
    private var hasSelectType = 0
    private var imgList = java.util.ArrayList<String>()
    var size = 0
    private var type = ""
    private var isLastQuestion = false
    private var xiaojieid = ""
    private var ifzt = ""
    private var currentPosition = 0
    private var maxPosition = 0 //已答最大题目数
    private var questionType = ""
    private var textWatcher: TextWatcher? = null
    private lateinit var imgListEach: ArrayList<ArrayList<LocalMedia>>

    override fun iniView() {
        listBean = ArrayList()
        listBeanAnswer = ArrayList()
        imgListEach = ArrayList()
        questionType = getIntentString("questionType")
        xiaojieid = getIntentString("xiaojieid")
        ifzt = getIntentString("ifzt")
        getData()
        binding.apply {
            tvQuestionType.setRoundRectBg(Color.parseColor("#4B6AEF"), dp2px(3f).toInt())
//            binding.selectImageVideo.selectImages(
//                localMediaList,
//                this@PracticeAnswerAct,
//                1,
//                9,
//                1,
//                true,
//                onClick = { }) { it ->
//                size = it.size
//                imgList.clear()
//                localMediaList.clear()
//                localMediaList.addAll(it)
//                imgListEach[currentPosition].clear()
//                imgListEach[currentPosition].addAll(it)
//            }
        }
    }

    private fun getData() {
        scopeNetLife {
            when (questionType) {
                "2" -> {
                    listBean.addAll(getpingjiatimu(xiaojieid)!!)
                    if (listBean != null && listBean.size > 0) {
                        setCurrentView(currentPosition)
                        for (i in 0 until listBean.size) {
                            var topicListDto = TopicListDto2(listBean[i].id!!)
                            listBeanAnswer.add(topicListDto)
                            val imgList = ArrayList<LocalMedia>()
                            imgListEach.add(imgList)
                        }

                    }
                }

                else -> {
                    listBean.addAll(gettimu(xiaojieid)!!)
                    if (listBean != null && listBean.size > 0) {
                        setCurrentView(currentPosition)
                        for (i in 0 until listBean.size) {
                            var topicListDto = TopicListDto2(listBean[i].id!!)
                            listBeanAnswer.add(topicListDto)
                            val imgList = ArrayList<LocalMedia>()
                            imgListEach.add(imgList)
                        }
                    }
                }
            }


        }
    }

    @SuppressLint("SetTextI18n")
    private fun setCurrentView(currentPosition: Int) {
        binding.apply {
            if (currentPosition == 0 && listBean.size != 1) {
                btnPrevious.gone()
                btnNext.visible()
                btnNext.background = getDrawable(R.drawable.shape_btn_main_27dp)
                btnNext.setTextColor(Color.parseColor("#FFFFFF"))
            } else if (currentPosition + 1 == listBean.size) {
                btnPrevious.visible()
                btnNext.background = getDrawable(R.drawable.shape_rect_e2e7ff_27dp)
                btnNext.setTextColor(Color.parseColor("#4B6AEF"))
                btnNext.text = "提交"
            } else {
                btnPrevious.visible()
                btnNext.visible()
                btnNext.background = getDrawable(R.drawable.shape_rect_e2e7ff_27dp)
                btnNext.setTextColor(Color.parseColor("#4B6AEF"))
                btnNext.text = "下一题"
            }

            tvQuestionNo.text = (currentPosition + 1).toString() + "/" + listBean.size
            when (listBean[currentPosition].type) {
                "1" -> {
                    tvTitle.text =
                        "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "()"
                    tvQuestionType.text = "单选题"
                    rcvAnswer.visible()
                    llSubjective.gone()
                    rcvAnswer.choiceQuestionAnswer("").apply {
                        R.id.rl.onClick {
                            models?.forEach {
                                (it as Options).isRightKey = false
                            }
                            (models?.get(modelPosition) as Options).isRightKey = true
                            when (modelPosition) {
                                0 -> listBeanAnswer[currentPosition].answer = "A"
                                1 -> listBeanAnswer[currentPosition].answer = "B"
                                2 -> listBeanAnswer[currentPosition].answer = "C"
                                3 -> listBeanAnswer[currentPosition].answer = "D"
                                4 -> listBeanAnswer[currentPosition].answer = "E"
                            }

                            val stringTitle =
                                "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                            val spannableString = SpannableString(stringTitle)
//设置颜色
                            spannableString.setSpan(
                                ForegroundColorSpan(Color.parseColor("#009B93")),
                                spannableString.length - 3,
                                spannableString.length,
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                            )
                            tvTitle.text = spannableString

                            notifyDataSetChanged()
                        }
                    }.models = listBean[currentPosition].options
                }

                "2" -> {
                    tvTitle.text =
                        "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "()"
                    tvQuestionType.text = "多选题"
                    rcvAnswer.visible()
                    llSubjective.gone()
                    rcvAnswer.moreChoiceQuestionAnswer("").apply {
                        R.id.rl.onClick {
                            setChecked(modelPosition, !checkedPosition.contains(modelPosition))
                            var answer = ""
                            checkedPosition.sort()
                            for (i in 0 until checkedPosition.size) {
                                if (answer.isEmpty()) {
                                    answer = checkedPosition[i].toString()
                                } else {
                                    answer += "," + checkedPosition[i].toString()
                                }
                            }
                            answer = answer.replace("0", "A")
                            answer = answer.replace("1", "B")
                            answer = answer.replace("2", "C")
                            answer = answer.replace("3", "D")
                            answer = answer.replace("4", "E")
                            listBeanAnswer[currentPosition].answer = answer


                            val stringTitle =
                                "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                            val spannableString = SpannableString(stringTitle)
//设置颜色
                            spannableString.setSpan(
                                ForegroundColorSpan(Color.parseColor("#009B93")),
                                spannableString.length - listBeanAnswer[currentPosition].answer?.length!! - 2,
                                spannableString.length,
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                            )
                            tvTitle.text = spannableString


                            notifyDataSetChanged()
                        }
                    }.models = listBean[currentPosition].options
                }

                "3" -> {
                    imgList.clear()
                    localMediaList.clear()
                    initSelectImage()
                    tvTitle.text =
                        "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title
                    tvQuestionType.text = "主观题"
                    rcvAnswer.gone()
                    llSubjective.visible()
                    if (textWatcher != null)
                        etSubjective.removeTextChangedListener(textWatcher)
                    etSubjective.setText("")
                    textWatcher = etSubjective.doAfterTextChanged {
                        listBeanAnswer[currentPosition].answer = it.toString()
                    }
                }

                else -> {
                    imgList.clear()
                    localMediaList.clear()
                    initSelectImage()
                    tvTitle.text = listBean[currentPosition].title
                    tvQuestionType.text = "评价题"
                    rcvAnswer.gone()
                    llSubjective.visible()
                    if (textWatcher != null)
                        etSubjective.removeTextChangedListener(textWatcher)

                    etSubjective.setText("")
                    textWatcher = etSubjective.doAfterTextChanged {
                        listBeanAnswer[currentPosition].answer = it.toString()
                    }
                }
            }
        }
    }

    private fun initSelectImage() {
        binding.selectImageVideo.selectImages(
            localMediaList,
            this@PracticeAnswerAct,
            1,
            9,
            1,
            true,
            onClick = { }) { it ->
            size = it.size
            imgList.clear()
            localMediaList.clear()
            localMediaList.addAll(it)
            imgListEach[currentPosition].clear()
            imgListEach[currentPosition].addAll(it)
        }
    }

    override fun onClick() {
        binding.apply {
            ivBack.onClick {
                finish()
            }

            btnNext.onClick {
                if (currentPosition < listBean.size - 1) {
                    currentPosition++
                    if (currentPosition > maxPosition) {
                        maxPosition = currentPosition
                        setCurrentView(currentPosition)
                    } else {
                        setCurrentViewPrevious(currentPosition)
                    }

                } else {
                    when (ifzt) {
                        "1" -> submittimuData()
//                        else -> submittimuData()
                        else -> toast("练习结束")
                    }

                }
            }

            btnPrevious.onClick {
                currentPosition--
                setCurrentViewPrevious(currentPosition)
            }
        }
    }

    private fun setCurrentViewPrevious(currentPosition: Int) {
        binding.apply {
            if (currentPosition == 0 && listBean.size != 1) {
                btnPrevious.gone()
                btnNext.visible()
                btnNext.background = getDrawable(R.drawable.shape_btn_main_27dp)
                btnNext.setTextColor(Color.parseColor("#FFFFFF"))
            } else if (currentPosition + 1 == listBean.size) {
                btnPrevious.gone()
                btnNext.text = "提交"
                btnNext.background = getDrawable(R.drawable.shape_rect_e2e7ff_27dp)
                btnNext.setTextColor(Color.parseColor("#4B6AEF"))
            } else {
                btnPrevious.visible()
                btnNext.visible()
                btnNext.text = "下一题"
                btnNext.background = getDrawable(R.drawable.shape_rect_e2e7ff_27dp)
                btnNext.setTextColor(Color.parseColor("#4B6AEF"))
            }

            if (listBeanAnswer[currentPosition].answer.isNullOrEmpty()) {
                setCurrentView(currentPosition)
            } else {


                tvQuestionNo.text = (currentPosition + 1).toString() + "/" + listBean.size
                when (listBean[currentPosition].type) {
                    "1" -> {
                        val stringTitle =
                            "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                        val spannableString = SpannableString(stringTitle)
//设置颜色
                        spannableString.setSpan(
                            ForegroundColorSpan(Color.parseColor("#009B93")),
                            spannableString.length - listBeanAnswer[currentPosition].answer?.length!! - 2,
                            spannableString.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        tvTitle.text = spannableString
                        tvQuestionType.text = "单选题"
                        rcvAnswer.visible()
                        llSubjective.gone()
                        rcvAnswer.choiceQuestionAnswer(listBeanAnswer[currentPosition].answer!!)
                            .apply {
                                R.id.rl.onClick {
                                    models?.forEach {
                                        (it as Options).isRightKey = false
                                    }
                                    (models?.get(modelPosition) as Options).isRightKey = true
                                    when (modelPosition) {
                                        0 -> listBeanAnswer[currentPosition].answer = "A"
                                        1 -> listBeanAnswer[currentPosition].answer = "B"
                                        2 -> listBeanAnswer[currentPosition].answer = "C"
                                        3 -> listBeanAnswer[currentPosition].answer = "D"
                                        4 -> listBeanAnswer[currentPosition].answer = "E"
                                    }

                                    val stringTitle =
                                        "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                                    val spannableString = SpannableString(stringTitle)
//设置颜色
                                    spannableString.setSpan(
                                        ForegroundColorSpan(Color.parseColor("#009B93")),
                                        spannableString.length - 3,
                                        spannableString.length,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                                    )
                                    tvTitle.text = spannableString

                                    notifyDataSetChanged()
                                }
                            }.models = listBean[currentPosition].options
                    }

                    "2" -> {
                        val stringTitle =
                            "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                        val spannableString = SpannableString(stringTitle)
//设置颜色
                        spannableString.setSpan(
                            ForegroundColorSpan(Color.parseColor("#009B93")),
                            spannableString.length - listBeanAnswer[currentPosition].answer?.length!! - 2,
                            spannableString.length,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        tvTitle.text = spannableString
                        tvQuestionType.text = "多选题"
                        rcvAnswer.visible()
                        llSubjective.gone()
                        rcvAnswer.moreChoiceQuestionAnswer(listBeanAnswer[currentPosition].answer!!)
                            .apply {
                                R.id.rl.onClick {
                                    setChecked(
                                        modelPosition,
                                        !checkedPosition.contains(modelPosition)
                                    )
                                    var answer = ""
                                    checkedPosition.sort()
                                    for (i in 0 until checkedPosition.size) {
                                        if (answer.isEmpty()) {
                                            answer = checkedPosition[i].toString()
                                        } else {
                                            answer += "," + checkedPosition[i].toString()
                                        }
                                    }
                                    answer = answer.replace("0", "A")
                                    answer = answer.replace("1", "B")
                                    answer = answer.replace("2", "C")
                                    answer = answer.replace("3", "D")
                                    answer = answer.replace("4", "E")
                                    listBeanAnswer[currentPosition].answer = answer


                                    val stringTitle =
                                        "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title + "(" + listBeanAnswer[currentPosition].answer + ")"
                                    val spannableString = SpannableString(stringTitle)
//设置颜色
                                    spannableString.setSpan(
                                        ForegroundColorSpan(Color.parseColor("#009B93")),
                                        spannableString.length - listBeanAnswer[currentPosition].answer?.length!! - 2,
                                        spannableString.length,
                                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                                    )
                                    tvTitle.text = spannableString


                                    notifyDataSetChanged()
                                }
                            }.models = listBean[currentPosition].options
                    }

                    "3" -> {
                        imgList.clear()
                        localMediaList.clear()
                        localMediaList.addAll(imgListEach[currentPosition])
                        initSelectImage()
                        tvTitle.text =
                            "(" + listBean[currentPosition].nums + "分) " + listBean[currentPosition].title
                        tvQuestionType.text = "主观题"
                        rcvAnswer.gone()
                        llSubjective.visible()

                        if (textWatcher != null)
                            etSubjective.removeTextChangedListener(textWatcher)
                        etSubjective.setText(listBeanAnswer[currentPosition].answer!!)
                        textWatcher = etSubjective.doAfterTextChanged {
                            listBeanAnswer[currentPosition].answer = it.toString()
                        }
                    }

                    else -> {
                        imgList.clear()
                        localMediaList.clear()
                        localMediaList.addAll(imgListEach[currentPosition])
                        initSelectImage()
                        tvTitle.text = listBean[currentPosition].title
                        tvQuestionType.text = "评价题"
                        rcvAnswer.gone()
                        llSubjective.visible()

                        if (textWatcher != null)
                            etSubjective.removeTextChangedListener(textWatcher)
                        etSubjective.setText(listBeanAnswer[currentPosition].answer!!)
                        textWatcher = etSubjective.doAfterTextChanged {
                            listBeanAnswer[currentPosition].answer = it.toString()
                        }
                    }
                }
            }
        }
    }

    private var uploadImgFlag = true//上传图片完成标识  false上传中   true上传完成

    /**
     *@Description 提交答题结果
     *@date 创建时间2024/2/24
     *
     */
    private fun submittimuData() {
        for (i in 0 until imgListEach.size) {
            val files = ArrayList<File>()

            for (j in 0 until imgListEach[i].size) {
                val filePath: String = imgListEach[i][j].realPath
                val file = File(filePath)
                files.add(file)
            }
            if (files.size == 0) {
                scopeNetLife {
                    if (i == imgListEach.size - 1 && uploadImgFlag) {
                        val baseBean = submittimu(xiaojieid, listBeanAnswer)
                        if (baseBean.result == "0") {
                            start(CommentDetailAct::class.java) {
                                putExtra("type", "1")
                                putExtra("id", baseBean.paperid)
                                putExtra("xiaojieid", xiaojieid)
                                putExtra("fromAct", "3")
                            }
                            sendEvent("", "refreshDaGang")
                            finish()
                        } else {
                            toast(baseBean.resultNote.toString())
                        }
                    }
                }
            } else {
                scopeNetLife {
                    uploadImgFlag = false
                    val baseBean = uploadFiles(files)
                    if (baseBean.result == "0") {
                        uploadImgFlag = true
                        var imgUrls = ""
                        for (k in 0 until baseBean.urls?.size!!) {
                            imgUrls = if (imgUrls.isEmpty()) {
                                baseBean.urls!![k]
                            } else {
                                imgUrls + "|" + baseBean.urls!![k]
                            }
                        }
                        listBeanAnswer[i].answerimage = imgUrls

                        if (i == imgListEach.size - 1 && uploadImgFlag) {
                            val baseBean = submittimu(xiaojieid, listBeanAnswer)
                            if (baseBean.result == "0") {
                                start(CommentDetailAct::class.java) {
                                    putExtra("type", "1")
                                    putExtra("id", baseBean.paperid)
                                    putExtra("xiaojieid", xiaojieid)
                                    putExtra("fromAct", "3")
                                }
                                sendEvent("", "refreshDaGang")
                                finish()
                            } else {
                                toast(baseBean.resultNote.toString())
                            }
                        }
                    }
                }
            }
        }
    }


}